package cn.weekimwee.map3d

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import cn.weekimwee.map3d.utilk.MyDrivingRouteOverlay
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.BitmapDescriptorFactory
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.amap.api.maps.model.Marker
import com.amap.api.maps.utils.SpatialRelationUtil
import com.amap.api.maps.utils.overlay.SmoothMoveMarker
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.route.*
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main5.*
import org.jetbrains.anko.toast
import java.util.concurrent.TimeUnit
import org.reactivestreams.Subscriber


class Main5Activity : AppCompatActivity() {

    private lateinit var aMap: AMap
    private lateinit var smoothMarker: SmoothMoveMarker

    //    private val endPoint = LatLonPoint(29.86088, 121.593371) 121.517715,29.942418
    private val startPoint = LatLonPoint(29.85284, 121.580157)
    private val endPoint = LatLonPoint(/*29.832463*/29.857822, 121.580062)
    //121.525386,29.923103 121.51624,29.94834
    private val passedPoint = arrayListOf(LatLonPoint(/*29.863953*//*29.85648*//*29.946457*/29.857822, 121.580062/*121.515961*//*121.581642*//*121.578438*/))

    private var oldLatLonArray = arrayListOf<LatLng>()
    private var newLatLonArray = arrayListOf<LatLng>()
    private var runArray = arrayListOf<LatLng>()

    private var isFirst = true//是否第一次进入
    private lateinit var drivingRouteOverlay: MyDrivingRouteOverlay

    private lateinit var routeSearch: RouteSearch
    private var disposable :Disposable?=null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main5)
        mapView.onCreate(savedInstanceState)
        aMap = mapView.map
        smoothMarker = SmoothMoveMarker(aMap)
        routeSearch = RouteSearch(this).apply {
            calculateDriveRouteAsyn(RouteSearch.DriveRouteQuery(RouteSearch.FromAndTo(startPoint, passedPoint[0]), RouteSearch.DrivingDefault, passedPoint, null, ""))
            setRouteSearchListener(object : RouteSearch.OnRouteSearchListener {
                override fun onDriveRouteSearched(p0: DriveRouteResult?, p1: Int) {
                    if (p1 == AMapException.CODE_AMAP_SUCCESS) {
                        if (!isFirst && oldLatLonArray.isNotEmpty() && newLatLonArray.isNotEmpty()) {
                            oldLatLonArray.clear()
                            oldLatLonArray.addAll(newLatLonArray)
                            newLatLonArray.clear()
                        }
                        p0?.paths?.let {
                            Log.e("eeeee", "result.size->${it.size},导航策略->${it[0].strategy}")
                            it[0].steps.forEach {
                                Log.e("eeeee", "道路名称-->${it.road}")
                                it.polyline.forEach {
                                    Log.e("eeeee", "坐标点-->lat->${it.latitude},lng->${it.longitude}")
                                    if (isFirst) {
                                        oldLatLonArray.add(LatLng(it.latitude, it.longitude))
                                        newLatLonArray.add(LatLng(it.latitude, it.longitude))
                                    } else {
                                        newLatLonArray.add(LatLng(it.latitude, it.longitude))
                                    }

                                }
                            }
                            runArray.apply {
                                clear()
                                add(oldLatLonArray[0])
                                add(newLatLonArray[0])
                            }
                            var drivePath = it[0]
                            var listPath = arrayListOf<LatLng>()
                            run outside@ {
                                drivePath.steps.forEach {
                                    it.polyline.forEach {
                                        if (it.latitude == passedPoint[0].latitude && it.longitude == passedPoint[0].longitude) return@outside
                                        else listPath.add(LatLng(it.latitude, it.longitude))
                                    }
                                }
                            }
//                            aMap.moveCamera(CameraUpdateFactory.changeLatLng(LatLng(29.946063,121.515803)))
                            //画路线
                            drivingRouteOverlay = MyDrivingRouteOverlay(this@Main5Activity, aMap, drivePath, p0.startPos, p0.targetPos, passedPoint, listPath).apply {
                                setNodeIconVisibility(false)
                                setIsColorfulline(false)
                                removeFromMap()
                                addToMap()
                                zoomToSpan()
                            }
                            startMove()
                        }
                    } else {
                        toast("未规划到数据")
                    }
                }

                override fun onBusRouteSearched(p0: BusRouteResult?, p1: Int) {

                }

                override fun onRideRouteSearched(p0: RideRouteResult?, p1: Int) {

                }

                override fun onWalkRouteSearched(p0: WalkRouteResult?, p1: Int) {

                }

            })
        }
        start.setOnClickListener {
            //实际上是不停的请求接口  直道数组加载完毕
            disposable =Observable.timer(5, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .repeat()
                    .subscribe({
                        Log.e("eeeee", "next--->")

                        //开始平滑移动
                        if (newLatLonArray.size >2) {
                            if (runArray.size != 0) {
                                runArray.removeAt(0)
                                runArray.add(newLatLonArray.removeAt(0))
                            } else{
                                runArray.add(newLatLonArray.removeAt(0))
                                runArray.add(newLatLonArray.removeAt(0))
                            }
                            if (smoothMarker != null) smoothMarker.destroy()
                            startMove()
                        }else{
                            disposable?.dispose()
                        }
//                        drivingRouteOverlay.removeStartMarker()
                        isFirst = false
                    }, {
                        it.printStackTrace()
                        Log.e("eeeee", "error--->${it.message}")
                    })
        }
    }

    override fun onResume() {
        super.onResume()
        mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle?) {
        super.onSaveInstanceState(outState)
        mapView.onSaveInstanceState(outState)
    }

    override fun onDestroy() {
        super.onDestroy()
        mapView.onDestroy()
    }

    private fun startMove() {
//        var bounds = LatLngBounds(newLatLonArray[0], newLatLonArray[newLatLonArray.size-2])
//        aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100))

        smoothMarker.setDescriptor(BitmapDescriptorFactory.fromResource(R.drawable.icon_car))

        // 取轨迹点的第一个点 作为 平滑移动的启动
        val drivePoint = runArray[0]
        val pair = SpatialRelationUtil.calShortestDistancePoint(runArray, drivePoint)
        runArray[pair.first] = drivePoint
        val subList = newLatLonArray.subList(pair.first, runArray.size)

        // 设置轨迹点
        smoothMarker.setPoints(subList)
        // 设置平滑移动的总时间  单位  秒
        smoothMarker.setTotalDuration(5)

        // 设置  自定义的InfoWindow 适配器
        aMap.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoWindow(marker: Marker): View? {
                return null
            }

            override fun getInfoContents(marker: Marker): View? {
                return null
            }
        })
        // 显示 infowindow
        smoothMarker.marker.showInfoWindow()
        smoothMarker.startSmoothMove()
    }
}
